package net.trombonium.steroid;

import java.io.*;
import java.util.zip.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration; 

import android.util.Log;

public class SteroidZip {
	private static final String TAG = "ZIpper";

	public static void ZipMe(String inputFile, String outputFile) {
		try{
			File inFolder=new File(inputFile);
			File outFolder=new File(outputFile);

			ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));

			BufferedInputStream in = null;
			byte[] data    = new byte[1000];
			String files[] = inFolder.list();
			for (int i=0; i<files.length; i++){                  
				in = new BufferedInputStream(new FileInputStream (inputFile+"/"+files[i]), 1000);   //Zip all the files in Result directory          
				out.putNextEntry(new ZipEntry(files[i])); 
				int count;
				while((count = in.read(data,0,1000)) != -1){
					out.write(data, 0, count);
				}
				out.closeEntry();
			}
			out.flush();
			out.close();
		}
		catch(Exception e){
			e.printStackTrace();
		} 
	}

	public static ArrayList<String> unzipAll(String inputFile, String outputDirectory) throws IOException{
		Log.i(TAG, "Unzip all");
		ArrayList<String> zips = UnZipMe(inputFile, outputDirectory);
		ArrayList<String> sqls = new ArrayList<String>();
		for(int i=0; i<zips.size(); ++i){
			String dir = zips.get(i);
			dir = dir.substring(0, dir.lastIndexOf(".")) + "/";  //chop off ".zip"
			(new File(dir)).mkdir();
			UnZipMe(zips.get(i), dir);
			sqls.add(dir+"sql");
		}
		return sqls;
	}
	
	public static ArrayList<String> UnZipMe(String inputFile, String outputDirectory) throws IOException {
		ZipFile zf = new ZipFile(inputFile);

		Enumeration e = zf.entries();
		ArrayList<String> extractedFiles = new ArrayList();
		
		while (e.hasMoreElements()) {
			ZipEntry ze = (ZipEntry) e.nextElement();
			String filename = outputDirectory + ze.getName();
			extractedFiles.add(filename);
			FileOutputStream fout = new FileOutputStream(filename);
			InputStream in = zf.getInputStream(ze);
			for (int c = in.read(); c != -1; c = in.read()) {
				fout.write(c);
			}
			in.close();
			fout.close();
		}
		Log.i(TAG, "Unzipped a file");
		return extractedFiles;
	}

}
